<template>
  <div>
    <!-- 分配角色组件 -->
    <el-checkbox-group v-model="roleIds">
      <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
        {{ item.name }}
      </el-checkbox>
    </el-checkbox-group>
    <!-- 渲染角色列表 -->

    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button type="primary" size="small" @click="addRole">确定</el-button>
        <el-button size="small" @click="cancleDialog">取消</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// 导入Api
import { getRoles } from '@/api/setting'
import { getUserDetailById } from '@/api/user'
import { assignRoles } from '@/api/employees'
export default {
  name: 'AssignRole',
  props: {
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }

  },
  data() {
    return {
      roleIds: [], // 复选框保存选中的列表数组
      roleList: [] // 角色列表数据
    }
  },
  created() {
    // 调用获取角色复选框方法
    this.getRoles()
    // 调用获取当前员工详情方法
    this.getUserDetailById()
  },
  methods: {
    // 取消弹框
    cancleDialog() {
      this.$emit('close')
    },
    // 获取当前员工详情
    async  getUserDetailById() {
      const res = await getUserDetailById(this.userId)
      this.roleIds = res.data.roleIds
    },
    // 获取角色复选框数据
    async  getRoles() {
      const res = await getRoles()
      // 赋值给复选框
      this.roleList = res.data.rows
    },
    // 确定新增权限
    async addRole() {
      const res = await assignRoles({ id: this.userId, roleIds: this.roleIds })
      // 用户提示
      this.$message.success(res.message)
      // 父组件-关闭弹窗
      this.$emit('close')
      // 重新获取数据
      this.getRoles()
    }
  }
}
</script>

<style lang="scss" scoped>
.footer {
  margin-top: 30px;
}
</style>
